using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Commands;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.Permissions.Interfaces;
using MediatR;

namespace Identity.Application.PermissionKeyResourceIds.CommandHandlers
{

    public class ChangApiIsActiveCommandHandler : IRequestHandler<ChangApiIsActiveCommand, Result>
    {
        private readonly IApiPermissionBindingRepository _permissionKeyResourceIdRepository;
        private readonly IPermissionsReadService _permissionsReadService;
        private readonly IUnitOfWork _unitOfWork;
        public ChangApiIsActiveCommandHandler(IApiPermissionBindingRepository permissionKeyResourceIdRepository,IPermissionsReadService permissionsReadService, IUnitOfWork unitOfWork)
        {
            _permissionKeyResourceIdRepository = permissionKeyResourceIdRepository;
            _permissionsReadService = permissionsReadService;
            _unitOfWork = unitOfWork;
        }
        public async Task<Result> Handle(ChangApiIsActiveCommand request, CancellationToken cancellationToken)
        {
            var apiPermission = _permissionKeyResourceIdRepository.GetByResourceId(request.resourceId);
            if (apiPermission == null) return Result.Failure("数据不存在");

            if (request.isActive)
            {
                if (apiPermission.permissionId == null) return Result.Failure("未绑定权限，无法启用");
                var permission =await _permissionsReadService.GetByIdAsync((Guid)apiPermission.permissionId);
                if (permission == null) return Result.Failure("未绑定权限，无法启用");
            }
            apiPermission.ChangeActive(request.isActive);

            await _unitOfWork.SaveChangesAsync(cancellationToken);
            return Result.Success(request.isActive);
        }
    }
}